<template>
  <e-container :loading="loading">
    <e-title title="Mail Settings" />
    <a-divider />
    <div class="form">
      <a-form ref="formRef" :model="apiData" layout="vertical">
        <a-form-item label="Invoice File Email To" name="emailTo">
          <a-row class="checkbox-table">
            <a-col :span="24" class="check-all">
              <a-form-item-rest>
                <a-checkbox v-model:checked="mailToAllChecked" :indeterminate="mailToSomeChecked"> All </a-checkbox>
              </a-form-item-rest>
            </a-col>
          </a-row>
          <a-checkbox-group v-model:value="apiData.emailTo" style="width: 100%">
            <a-row class="checkbox-table">
              <a-col v-for="option in emailToCandidates" :key="option.id" :span="8" :title="option.name">
                <a-checkbox :value="option.id" :disabled="!option.enable">
                  <div class="person-name">{{ option.name }}</div>
                  <div class="person-type">{{ option.type }}</div>
                </a-checkbox>
              </a-col>
              <a-col
                v-for="index in 3 - (emailToCandidates.length % 3 === 0 ? 3 : emailToCandidates.length % 3)"
                :key="index"
                :span="8"
              />
            </a-row>
          </a-checkbox-group>
        </a-form-item>
        <a-form-item label="Invoice File Email Cc" name="emailCC">
          <a-row class="checkbox-table">
            <a-col :span="24" class="check-all">
              <a-form-item-rest>
                <a-checkbox v-model:checked="mailCcAllChecked" :indeterminate="mailCcSomeChecked"> All </a-checkbox>
              </a-form-item-rest>
            </a-col>
          </a-row>
          <a-checkbox-group v-model:value="apiData.emailCc" style="width: 100%">
            <a-row class="checkbox-table">
              <a-col v-for="option in emailCcCandidates" :key="option.id" :span="8" :title="option.name">
                <a-checkbox :value="option.id" :disabled="!option.enable">
                  <div class="person-name">{{ option.name }}</div>
                  <div class="person-type">{{ option.type }}</div>
                </a-checkbox>
              </a-col>
              <a-col
                v-for="index in 3 - (emailCcCandidates.length % 3 === 0 ? 3 : emailCcCandidates.length % 3)"
                :key="index"
                :span="8"
              />
            </a-row>
          </a-checkbox-group>
        </a-form-item>
      </a-form>
    </div>
    <a-divider />
    <div class="buttons">
      <a-space size="middle">
        <a-button @click="handleCancel">Cancel</a-button>
        <a-button v-permission="'FinancialInformation:Mail:Edit'" type="primary" @click="handleSave">Save</a-button>
      </a-space>
    </div>
  </e-container>
</template>

<script setup>
import { ref, reactive, inject, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { CONFIRM_BACK_TO_DETAIL, SAVED_SUCCESSFULLY } from '@/constants/message'
import financial from '@/api/client/financial.js'
import EContainer from '@/components/EContainer.vue'
import ETitle from '@/components/ETitle.vue'

const route = useRoute()
const router = useRouter()
const emits = defineEmits(['updated'])
const { id } = route.params
const { Modal, message } = inject('Feedback')
const loading = ref(true)
const formRef = ref(null)
const apiData = reactive({
  emailTo: [],
  emailCc: []
})
const toCandidatesData = ref({})
const ccCandidatesData = ref({})
const emailToCandidates = computed(() => {
  const items = []
  Object.keys(toCandidatesData.value)
    // 先排除ccHistory
    .filter(key => key !== 'ccHistory')
    .forEach(key => {
      if (Array.isArray(toCandidatesData.value[key])) {
        toCandidatesData.value[key].forEach(value => {
          const item = {
            raw: value,
            id: key + ',' + value.id,
            name: undefined,
            type: undefined,
            sendType: value.emailType ? (value.emailType === 1 ? 'to' : 'cc') : 'to',
            checked: value.check,
            enable: true
          }
          if (apiData.emailCc.find(id => id === item.id)) item.enable = false
          if (key === 'contact') {
            item.name = value.contactName
            item.type = value.contactTypeName
          }
          if (key === 'contactDepartment') {
            item.name = value.departmentName
            item.type = 'Department Contact'
          }
          if (key === 'eciContact') {
            item.name = value.displayName
            item.type = value.type === 1 ? 'Sales' : value.type === 2 ? 'PM' : 'AM'
          }
          if (key === 'toHistory') {
            item.name = value.email
            item.type = 'Past Data'
            item.checked = true
          }
          items.push(item)
        })
      }
    })
  return items
})

const mailToAllChecked = computed({
  get() {
    return (
      emailToCandidates.value.filter(item => item.enable).length > 0 &&
      emailToCandidates.value.filter(item => item.enable).length === apiData.emailTo.length
    )
  },
  set(value) {
    apiData.emailTo = []
    if (value) {
      apiData.emailTo.push(...emailToCandidates.value.filter(item => item.enable).map(item => item.id))
    }
  }
})
const mailToSomeChecked = computed(
  () =>
    apiData.emailTo.length > 0 && apiData.emailTo.length < emailToCandidates.value.filter(item => item.enable).length
)

const emailCcCandidates = computed(() => {
  const items = []
  Object.keys(ccCandidatesData.value)
    // 先排除toHistory
    .filter(key => key !== 'toHistory')
    .forEach(key => {
      if (Array.isArray(ccCandidatesData.value[key])) {
        ccCandidatesData.value[key].forEach(value => {
          const item = {
            raw: value,
            id: key + ',' + value.id,
            name: undefined,
            type: undefined,
            sendType: value.emailType ? (value.emailType === 1 ? 'to' : 'cc') : 'cc',
            checked: value.check,
            enable: true
          }
          if (apiData.emailTo.find(id => id === item.id)) item.enable = false
          if (key === 'contact') {
            item.name = value.contactName
            item.type = value.contactTypeName
          }
          if (key === 'contactDepartment') {
            item.name = value.departmentName
            item.type = 'Department Contact'
          }
          if (key === 'eciContact') {
            item.name = value.displayName
            item.type = value.type === 1 ? 'Sales' : value.type === 2 ? 'PM' : 'AM'
          }
          if (key === 'ccHistory') {
            item.name = value.email
            item.type = 'Past Data'
            item.checked = true
          }
          items.push(item)
        })
      }
    })
  return items
})

const mailCcAllChecked = computed({
  get() {
    return (
      emailCcCandidates.value.filter(item => item.enable).length > 0 &&
      emailCcCandidates.value.filter(item => item.enable).length === apiData.emailCc.length
    )
  },
  set(value) {
    apiData.emailCc = []
    if (value) {
      apiData.emailCc.push(...emailCcCandidates.value.filter(item => item.enable).map(item => item.id))
    }
  }
})
const mailCcSomeChecked = computed(
  () =>
    apiData.emailCc.length > 0 && apiData.emailCc.length < emailCcCandidates.value.filter(item => item.enable).length
)

/**
 * 加载可选项并分类处理
 */
financial
  .getEmailCandidateList(id)
  .then(([toList, ccList]) => {
    loading.value = false
    toCandidatesData.value = toList.data
    ccCandidatesData.value = ccList.data
    nextTick(() => {
      emailToCandidates.value.forEach(item => {
        if (item.checked && item.sendType === 'to') apiData.emailTo.push(item.id)
      })
      emailCcCandidates.value.forEach(item => {
        if (item.checked && item.sendType === 'cc') apiData.emailCc.push(item.id)
      })
    })
  })
  .finally(() => {
    loading.value = false
  })

/**
 * 保存
 */
const handleSave = () => {
  const data = {
    clientID: id,
    mailSettings: [],
    toHistory: [],
    ccHistory: []
  }
  apiData.emailTo.forEach(item => {
    const params = item.split(',')
    const record = {
      id: parseInt(params[1]),
      emailType: 1,
      bizType: undefined
    }
    if (params[0] === 'contactDepartment') {
      record.bizType = 1
      data.mailSettings.push(record)
    }
    if (params[0] === 'contact') {
      record.bizType = 2
      data.mailSettings.push(record)
    }
    if (params[0] === 'eciContact') {
      record.bizType = 3
      data.mailSettings.push(record)
    }
    if (params[0] === 'toHistory') {
      data.toHistory.push(parseInt(params[1]))
    }
  })
  apiData.emailCc.forEach(item => {
    const params = item.split(',')
    const record = {
      id: parseInt(params[1]),
      emailType: 2,
      bizType: undefined
    }
    if (params[0] === 'contactDepartment') {
      record.bizType = 1
      data.mailSettings.push(record)
    }
    if (params[0] === 'contact') {
      record.bizType = 2
      data.mailSettings.push(record)
    }
    if (params[0] === 'eciContact') {
      record.bizType = 3
      data.mailSettings.push(record)
    }
    if (params[0] === 'ccHistory') {
      data.ccHistory.push(parseInt(params[1]))
    }
  })

  financial.setEmailSettings(data).then(() => {
    message.success(SAVED_SUCCESSFULLY)
    router.push({ name: 'Financial Information' })
    emits('updated')
  })
}

/**
 * 取消模态框
 */
const handleCancel = () => {
  Modal.confirm({
    content: CONFIRM_BACK_TO_DETAIL,
    okButtonProps: { danger: true },
    onOk: () => {
      router.push({ name: 'Financial Information' })
      emits('updated')
    }
  })
}
</script>

<style scoped lang="less">
.form {
  padding: 0 228px;
}
.buttons {
  text-align: center;
}
.ant-divider {
  border-top: 1px solid #dcdee7 !important;
}
.ant-form {
  .checkbox-table {
    .check-all {
      background-color: @bg-color;
      border: 1px solid @border-color;
      line-height: 40px;
      padding: 0 16px;
    }
    .person-name {
      user-select: none;
      line-height: 24px;
    }
    .person-type {
      user-select: none;
      word-break: break-all;
      line-height: 24px;
      font-size: 12px;
      color: @text-gray;
    }
    .ant-col-8 {
      line-height: 32px;
      padding: 0 16px;
      border-left: 1px solid @border-color;
      border-bottom: 1px solid @border-color;
      overflow: hidden;
      &:nth-child(3n) {
        border-right: 1px solid @border-color;
      }
      &:last-child {
        border-right: 1px solid @border-color;
      }
    }
  }
}
</style>
<route lang="yaml">
name: Mail Settings
path: '/client/:id/financial-information/mail-settings'
meta:
  title: Mail Settings
  permission: FinancialInformation
</route>
